package model

import (
	"gorm.io/gorm"
	"next-vue-backend/utils/errmsg"
)

type Category struct {
	CategoryId int    `gorm:"primary_key;auto_increment" json:"category_id"`
	Name       string `gorm:"type:varchar(20);not null" json:"name"`
}

// CheckCategory 查询分类是否存在
func CheckCategory(name string) int {
	var category Category
	db.Select("category_id").Where("name = ?", name).First(&category)
	if category.CategoryId > 0 {
		return errmsg.ERROR_CATENAME_USED
	}
	return errmsg.SSUCCESS
}

// CreateCategory 创建分类
func CreateCategory(data *Category) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}

// todo 查询所有分类下的文章

// GetCategorys 查询分类列表
func GetCategorys(pageSize int, pageNum int) ([]Category, int64) {
	var category []Category
	var total int64
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&category).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return category, total
}

// EditCategory 编辑分类
func EditCategory(id int, data *Category) int {
	var category Category
	var maps = make(map[string]interface{})
	maps["name"] = data.Name
	err = db.Model(&category).Where("category_id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}

	return errmsg.SSUCCESS

}

// DeleteCategory 删除分类
func DeleteCategory(id int) int {
	var category Category
	err = db.Where("category_id = ? ", id).Delete(&category).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SSUCCESS
}
